package com.hzc.springchan.config.velocity;

import com.hzc.springchan.constant.System;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * velocity模板配置类，仅供本地使用
 * @author chen990627
 * @date 2022/10/11
 */
@Configuration
@ConditionalOnProperty(  //如果属性跟spring配置里的一样，则注解的配置类生效
        name = "custom.datasource.url",
        havingValue = "jdbc:mysql://localhost:3306/springchan?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true"
)
public class VelocityConfig {

    private final static String ENTITY_TEMPLATE_PATH = "templates/Entity.java.vm";

    private final static String MAPPER_INTER_TEMPLATE_PATH = "templates/Mapper.java.vm";

    private final static String MAPPER_XML_TEMPLATE_PATH = "templates/Mapper.xml.vm";

    @Bean
    public VelocityEngine velocityEngine() {
        //创建velocity引擎
        VelocityEngine velocityEngine = new VelocityEngine();
        //初始化环境
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();
        return velocityEngine;
    }

    @Bean
    public VelocityContext velocityContext() {
        VelocityContext velocityContext = new VelocityContext();
        return velocityContext;
    }

    @Bean(System.VelocityBean.ENTITY_TEMPLATE)
    public Template entityTemplate(VelocityEngine engine) {
        return engine.getTemplate(ENTITY_TEMPLATE_PATH);
    }

    @Bean(System.VelocityBean.MAPPER_INTER_TEMPLATE)
    public Template mapperInterTemplate(VelocityEngine engine) {
        return engine.getTemplate(MAPPER_INTER_TEMPLATE_PATH);
    }

    @Bean(System.VelocityBean.MAPPER_XML_TEMPLATE)
    public Template mapperXmlTemplate(VelocityEngine engine) {
        return engine.getTemplate(MAPPER_XML_TEMPLATE_PATH);
    }
}
